package com.yf.service.course.impl;

import com.yf.dao.course.*;
import com.yf.entity.course.*;
import com.yf.enums.PayStatusEnum;
import com.yf.response.RRException;
import com.yf.service.impl.BaseServiceImpl;
import com.yf.utils.CommonUtil;
import com.yf.vo.OrderBackVo;
import com.yf.vo.OrderPayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.yf.service.course.LessonOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Tue Oct 23 17:22:49 CST 2018
 */
@Service
public class LessonOrderServiceImpl extends BaseServiceImpl<LessonOrderEntity> implements LessonOrderService {
    @Autowired
    private LessonOrderDao lessonOrderDao;

    @Autowired
    private LessonOrderItemDao lessonOrderItemDao;

    @Autowired
    private LessonDao lessonDao;

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private LessonRecordDao lessonRecordDao;



    /**内部方法**/


    /**外部方法实现**/

    /**
     * 提交订单
     * @param userId
     * @param id  lessonId 或者 courseId
     * @param handle:  购买类型   0，全章购买    1，单节购买
     */
    @Override
    @Transactional
    public OrderPayVO order(Long userId, Long id, Integer handle){
        //查询用户购买了哪些章节
        List<Long> paidList = getLessonByUser(userId);
        BigDecimal price;  //订单价格
        List<LessonOrderItemEntity> itemList = new ArrayList<>();  //订单详情list
        String orderInfo = "购买";
        //单节购买
        if(handle == 1){
            //先判断有没有购买此章节
            if(!paidList.isEmpty()){
                for (Long aLong : paidList) {
                    if(aLong.equals(id)){
                        throw new RRException("此章节已购买");
                    }
                }
            }

            //计算订单价格
            LessonEntity lessonEntity = lessonDao.get(id);
            price = lessonEntity.getPrice();

            LessonOrderItemEntity lessonOrderItemEntity = new LessonOrderItemEntity(id,price);
            itemList.add(lessonOrderItemEntity);

            orderInfo+=lessonEntity.getName();

        }else {  //全章购买
            List<LessonEntity> lessonList = lessonDao.getList(id);  //课程下的所有章节
            int size = lessonList.size();
            for (int i = lessonList.size() - 1; i >= 0; i--) {
                LessonEntity lessonEntity = lessonList.get(i);
                boolean isPaid = true;
                //剔除已经购买的章节
                if(!paidList.isEmpty()){
                    for (Long aLong : paidList) {
                        if(lessonEntity.getId().equals(aLong)){
                            lessonList.remove(i);
                            isPaid = false;
                            break;
                        }
                    }
                }
                if(isPaid){  //订单详情list加入未购买的章节
                    LessonOrderItemEntity lessonOrderItemEntity = new LessonOrderItemEntity(lessonEntity.getId(),lessonEntity.getPrice());
                    itemList.add(lessonOrderItemEntity);
                }
            }

            if(lessonList.isEmpty()){
                throw new RRException("此课程已购买");
            }

            //计算订单总价格
            CourseEntity courseEntity = courseDao.get(id);
            BigDecimal rate = new BigDecimal((double) lessonList.size()/size).setScale(2, BigDecimal.ROUND_HALF_UP);  //未购买的章节数：lessonList.size()
            price = (courseEntity.getPrice().multiply(rate)).setScale(2, BigDecimal.ROUND_HALF_UP);
            orderInfo+=courseEntity.getName();
        }


        //生成订单号
        String orderNo = CommonUtil.createNo();
        //保存订单
        LessonOrderEntity lessonOrderEntity = new LessonOrderEntity(orderNo,new Date(),userId,PayStatusEnum.UNPAID.getState(),price);
        lessonOrderDao.save(lessonOrderEntity);
        //保存订单详情
        for (LessonOrderItemEntity lessonOrderItemEntity : itemList) {
            lessonOrderItemEntity.setLessonOrder(lessonOrderEntity.getId());
        }
        lessonOrderItemDao.saveBatch(itemList);
        OrderPayVO orderPayVO = new OrderPayVO(orderNo,orderInfo,price);
        return orderPayVO;

    }

    /**
     * 获取用户购买了哪些章节
     */
    @Override
    public List<Long> getLessonByUser(Long userId){
        List<LessonOrderEntity> orderList = lessonOrderDao.getOrderByUser(userId,PayStatusEnum.PAID.getState());
        List<Long> list = new ArrayList();
        if(!orderList.isEmpty()){
            List<Long> oIdList = new ArrayList<>();
            for (LessonOrderEntity lessonOrderEntity : orderList) {
                oIdList.add(lessonOrderEntity.getId());
            }

            List<LessonOrderItemEntity> itemList = lessonOrderItemDao.getByOrder(oIdList);

            for (LessonOrderItemEntity lessonOrderItemEntity : itemList) {
                list.add(lessonOrderItemEntity.getLessonId());
            }

        }
        return list;
    }

    /**
     * 获取用户已提交未支付的章节
     */

    @Override
    public List<OrderBackVo> orderList(Map<String, Object> params) {
        return lessonOrderDao.orderList(params);
    }


    @Override
    public LessonOrderEntity getByOrderNo(String orderNo) {
        return lessonOrderDao.getByOrderNo(orderNo);
    }

    @Override
    public void updatePayStatus(String orderNo, String totalFee) {
        LessonOrderEntity lessonOrderEntity = lessonOrderDao.getByOrderNo(orderNo);
        Integer payStatus = 0;  //支付状态
        String payInfo = ""; //支付状态信息
        Integer payWay = 0;//支付方式

        //判断金额
        if(new BigDecimal(totalFee).compareTo(lessonOrderEntity.getPrice().multiply(new BigDecimal(100)))!=0){
            payStatus=PayStatusEnum.ERROR.getState();
            payInfo="金额错误，订单异常";
        }else if(!PayStatusEnum.PAID.getState().equals(lessonOrderEntity.getPayStatus())){  //改变支付状态
            payStatus=PayStatusEnum.PAID.getState();
            lessonOrderEntity.setPayInfo("支付成功");
        }

        lessonOrderEntity.setPayStatus(payStatus);
        lessonOrderEntity.setPayInfo(payInfo);
        lessonOrderEntity.setPayWay(payWay);
        lessonOrderDao.update(lessonOrderEntity);

    }

}
